package com.vf.cloud.pass.mvc.biz.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.vf.cloud.pass.common.datasource.annotation.Tx;
import com.vf.cloud.pass.common.domain.sys.Client;
import com.vf.cloud.pass.common.util.R;
import com.vf.cloud.pass.common.util.UuidUtil;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/client")
public class ClientController {

	@GetMapping(value = { "/list" }, produces = "application/json; charset=utf-8")
	public R<Page<Client>> findList(
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "status", required = false, defaultValue = "") String status,
			@RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
			@RequestParam(name = "limit", required = false, defaultValue = "10") int limit) throws Exception {

		String sqlExceptSelect = " FROM " + Client.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keywords)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keywords + "%' ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.TYPE DESC ";
		Page<Client> pages = Client.dao.paginate(cur, limit, "select * ", sqlExceptSelect);
		return R.ok(pages);
	}

	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Client> save(Client model) {
		try {
			if (StrKit.isBlank(model.getName())) {
				return R.failed("名称不可以为空！");
			}
			if (StrKit.notBlank(model.getId())) {
				if (model.update()) {
					return R.ok(model);
				} else {
					return R.failed("更新失败！");
				}
			} else {
				model.setId(UuidUtil.getUUID());
				if (model.save()) {
					return R.ok(model);
				} else {
					return R.failed("保存失败！");
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}
	
	

	@Tx
	@RequestMapping(value = "/deleteById", method = RequestMethod.GET)
	public R<String> deleteById(@RequestParam(name = "id") String id) throws Exception {
		try {
			Client sever = Client.dao.findById(id);
			if (sever == null)
				return R.failed("数据不存在，刷新后尝试!");
			if (sever.delete()) {
				return R.ok();
			}
			return R.failed("失败！");
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

}
